var conType = 'conNum'
    ,objCons = []
    ,valueType
    ,selectKey
    ,currentLayerIndex = 0
    ,createConnectionFlag = false
    ,layTable = layui.table
    ,layForm = layui.form
    ,actData = {}
    ,actType = 'add'
    ,conViewTemp = []
    ,form = layui.form
    ,partType = 0
    ,opType = 0
    ,arrBtn = []
    ,wfId = RequestURLParam.getParam("wfId")
    ,moduleId = RequestURLParam.getParam("moduleId");

layui.use('laydate', function () {
    var laydate = layui.laydate;

    laydate.render({
        elem: '#conDateValue' //指定元素
    });
})

layui.use(['element', "layer", "form"], function () {
    var element = layui.element,
        layer = layui.layer,
        form = layui.form

    form.render();

});


$(document).ready(function () {

    init();


});

function init() {

    jsPlumb.ready(function () {
        flowchart.init();
        getActivities();

    });
    $("body").droppable({
        drop: function (event, ui) {
            activityDrop(event, ui);
        }
    });


}
/*
* @author: wj
* @description: 新建活动/新建结束
* @date: 2019/3/4 19:30
* @param
* @return
*/
function createActivity(type) {
    var url = '/wf/activity/createActivity';

    var aData = {
        "wfId": wfId,
        "activityName": '新建活动',
        "activityType": type,
        "participateType": '2',
        "positionX": "10",
        "positionY": "10",
        "operationType": "4",
        "activityButtons": "10"
    }

    if (type == "end") {
        aData["activityName"] = '结束'
    }

    ActHttpRequest(url, aData, function (data) {
        if (data.OK !== "OK") {
            layer.alert(data.message);
            return;
        }
        var wfActivity = data.wfActivity;

        //显示流程图节点
        var node = getNodeHtml(wfActivity);
        $('#flowchart').append(node);
        var nodeId = $(node).attr('id');
        initJsPlumbEvent(nodeId);

        $('#' + nodeId).click(function () {
            flowchart.currentNode = this
        })

        $('#' + nodeId).dblclick(function () {
            var me = this;
            var id = $(me).attr('id');
            var title = $(me).find('.activity_title > div:first').html();
            getActivityAndShow(id, title);
        });

        $('#' + nodeId).draggable({})
    }, 'post', null, null, null, '加载中。。。');
}

/*
* @author: wj
* @description: 显示流程图节点
* @date: 2019/3/4 19:31
* @param
* @return
*/
function getNodeHtml(node) {

    var activityCode = node['activityCode'] || '';
    // if (activityCode == '') {
    //     layer.alert('有活动的“活动代码”为空，请检查！');
    // }
    var id = node['wfaId'] || '';
    var className = 'activity';
    var nodeName = node['activityName'];
    var executeUser = "【执行人】"
    var strTtemp
    if (node['activityType'] == 'start' || node['activityType'] == 'end') {
        className += ' ' + node['activityType'];
    }
    if (node['activityType'] == 'center') {
        className += ' center_node';
    }
    if (activityCode == "end" || activityCode == "start") {
        executeUser = ""
    } else if (activityCode == "001") {
        executeUser += "发起人"
    } else {
        strTtemp = getExecutor(id)
        if (!strTtemp) strTtemp = "（未配置）"
        executeUser += strTtemp
    }
    var html = '<div id="' + id + '" code="' + activityCode + '" class="' + className + '" activity_type="' + node['activityType'] + '" ' +
        'style="left:' + node['positionX'] + 'px;top:' + node['positionY'] + 'px;" title="' + executeUser + '">';
    html += '<span  class="activity_title"><div>' + nodeName + '</div><div>' + activityCode + '</div></span></br>';
    html += '</div>';

    return html;
}



/**
 * 连线时，检查连线是否有效
 */
function checkConnection(me, connInfo) {
    var sourceId = connInfo.sourceId;
    var targetId = connInfo.targetId;
    //检查开始/结束节点
    var sourceType = $('#' + sourceId).attr('activity_type');
    var targetType = $('#' + targetId).attr('activity_type');

    if (sourceType == 'end') {
        layer.msg('结束环节不能发起连线！');
        return;
    }
    if (targetType == 'start' || sourceType == 'start') {
        layer.msg('开始环节不能直接连线！');
        return;
    }
    if (sourceId == targetId) {
        layer.msg('起始节点不能是目标节点！');
        return;
    }
    //正向连线
    var connectionsForward = me.instance.getConnections({
        source: sourceId,
        target: targetId
    });
    //反向连线
    var connectionsReverse = me.instance.getConnections({
        source: targetId,
        target: sourceId
    });
    if (connectionsForward.length > 0) {
        layer.msg("已存在相同的连接线！")
        return false;
    } else {
        return true;
    }
    //分离反向线 up ↑↑
    if (connectionsForward.length <= 0 && connectionsReverse.length <= 0) {
        return true;
    }
    //有反向连线，不再创建连线，修改overlay，添加反向箭头
    if (connectionsReverse.length > 0) {

        var connection = connectionsReverse[0];
        addReverseOverlays(connection, function (connection) {
            //反向连线，修改连接点，并保存到数据库
                var endpoints = connection.endpoints;
                var sourcePoint = endpoints[1].getUuid();
                var targetPoint = endpoints[0].getUuid();
                var targetCode = $(connection.source).attr('code');
                var sourceCode = $(connection.target).attr('code');
                createConnection(sourceCode, sourcePoint, targetCode, targetPoint, wfCode);
        });
        return false;
    }
    return false;
}

/*
* @author: wj
* @description: 拖动活动以后，实时保存节点位置
* @date: 2019/3/5 17:08
* @param
* @return
*/
function activityDrop(event, ui) {
    var activity = ui.draggable[0],
        activityId = $(activity).attr('id'),
        positionX = $(activity).position().left,
        positionY = $(activity).position().top;

    ActHttpRequest('/wf/activity/update',
        {'wfaId': activityId,
         'positionX': positionX,
         'positionY': positionY},
        function (data) {}, 'post', null, null, null ,null);
}
/*
* @author: wj
* @description: 获取活动节点
* @date: 2019/3/4 19:31
* @param
* @return
*/
function getActivities() {
    var url = '/wf/activity/list';
    ActHttpRequest(url, {
        'wfId': wfId
    }, function (data) {
        if(!data)return;
        if (data.OK !== "OK") {
            layer.msg(data.message);
            return;
        }
        var list = data.List;
        if(!list || list.length == 0){
            return;
        }
        for (var i = 0; i < list.length; i++) {
            var activity = list[i];
            var node = getNodeHtml(activity);
            $('#flowchart').append(node);
        }
        initEvent();
        var activities = jsPlumb.getSelector("#flowchart .activity");
        for (var i = 0; i < activities.length; i++) {
            initJsPlumbEvent(activities[i])
        }

        getAllNextActivitiesAndConnect();

    }, 'post', null, null, '读取中。。。', true);
}

function initEvent() {
    $('.activity').click(function () {
        flowchart.currentNode = this
    })

    $('.activity').dblclick(function () {

        var me = this;
        var id = $(me).attr('id') || '';
        var title = $(me).find('.activity_title > div:first').html();
        var type = $(me).attr('activity_type');
        if (type == 'start') {
            layer.alert('开始环节不可编辑！',{icon: 4})
            return;
        }
        // getActivityAndShow(id,title);

        showNodeDetail()

    });
    //额外draggable，用于获取拖放事件，保存位置
    $(".activity").draggable({});
}
function initJsPlumbEvent(nodeID) {
    flowchart.addEndpoint(nodeID);
    flowchart.instance.draggable(nodeID);

}
/*
* @author: wj
* @description: 配置连线控制条件
* @date: 2019/3/5 17:12
* @param
* @return
*/
function showLineDetail() {
    var sourceId = flowchart.currentLine.sourceId
    var targetId = flowchart.currentLine.targetId
    var sourceCode = flowchart.currentLine.source.textContent.substr(2)

    if (sourceCode == 'start') {
        layer.alert('该控制线不可编辑！',{icon: 4})
        return
    }

    layer.open({
        type: 1
        , content: $('#lineDetail')
        , resize: false
        , area: ['720px', '550px']
        , title: '控制条件配置'
        , success: function (layero, index) {
            var previousNode = $('#' + flowchart.currentLine.sourceId).text()
            var nextNode = $('#' + flowchart.currentLine.targetId).text()

            currentLayerIndex = index;
            $('#previousNode').val(previousNode)
            $('#nextNode').val(nextNode)
            $('#conList').html('')
            objCons = []

            var url = '/wf/activity/line/getNodeData';

            ActHttpRequest(url, {
                'sourceId': sourceId,
                'targetId': targetId,
                'wfId': wfId,
            }, function (data) {
                if (data.OK != "OK") {
                    layer.alert(data.message);
                    return;
                }

                $("#conditionKey").html("")
                if(data.formField.length == 0 || data.formField == "[]" || data.formField == "") {
                    $("#conditionKey").append("<option id=\"\" value=\"\">无</option>")
                    conditionFormRender()
                } else {
                    $("#conditionKey").append("<option value=\"\">选择控制字段</option>")
                    var name_values = {}
                    $.each(data.formField, function (i, item) {
                        if (item.type != "textarea" && item.displayName != "单行文本框")
                            $("#conditionKey").append("<option value='" + item.name + "'>" + item.displayName + "</option>")

                        if (item.value)
                            name_values[item.name] = item.value

                    })
                    layForm.render();

                    objCons = []
                    if (data.List.length == 1) {
                        var o = data.List[0].conditions

                        if (o != null && o != "[]" && o != "" )
                            objCons = JSON.parse(data.List[0].conditions)
                            conViewTemp = JSON.parse(data.List[0].conditions)
                    }
                    conditionFormRender()
                    layForm.on('select(conditionKey)', function(data){

                        if (name_values.hasOwnProperty(data.value) && name_values[data.value].length > 0) {
                            $("#conditionKeyValue_div").css("display", "")
                            $("#conditionKeyValueText").css("display", "none")
                            valueType = "select"

                            var iArr = name_values[data.value]
                            $("#conditionKeyValue").html("")
                            $("#conditionKeyValue").append("<option value=''>选择控制值</option>")

                            if(iArr.length > 0) {
                                $.each(name_values[data.value], function (i, item) {
                                    $("#conditionKeyValue").append("<option value='" + item.value + "'>" + item.displayName + "</option>")
                                })
                            }
                        } else {
                            $("#conditionKeyValue_div").css("display", "none")
                            $("#conditionKeyValueText").css("display", "")
                            valueType = "text"
                        }

                        layForm.render()
                    });
                }

            }, null, null, null, '加载中。。。');
        }
        , end: function () {
            $('#lineDetail').css('display', 'none')

            flowchart.currentLine.removeOverlay("conLabel")

            flowchart.currentLine.setLabel({
                label:conObj2html(conViewTemp),
                location:0.36,
                id:"conLabel",
                labelStyle:{
                    color:"white",
                    fill:"gray"
                }
            })

            flowchart.currentLine = {}
            objCons = []
            conViewTemp = []
            clearCon()
        }
    });
}

/*
* 初始化条件表单
* */
function clearCon() {
    $("#conditionKey").val('')
    $("#oprator").val('')
    $("#conditionKeyValue").val('')
    $("#conditionKeyValueText").val('')
    layForm.render()
}
/*
* @author: wj
* @description: 活动连线增加控制条件
* @date: 2019/3/5 19:31
* @param
* @return
*/
function addConditon() {
    var objCon = {
        "fieldName": "",
        "fieldDisName": "",
        "operator": "",
        "operatorName": "",
        "conValue": "",
        "conValueName": ""
    }

    if ($("#conditionKey").val()) {
        var selectKey = $("#conditionKey option:selected")

        objCon.fieldName =selectKey.val()
        objCon.fieldDisName = selectKey.text()
    } else {
        layer.alert("请选择控制字段")
        return
    }

    if ($("#oprator").val()) {
        var selectKey = $("#oprator option:selected")

        objCon.operator =selectKey.val()
        objCon.operatorName = selectKey.text()
    } else {
        layer.alert("请选择关系")
        return
    }

    if (valueType == "select") {
        if ($("#conditionKeyValue").val()) {
            var selectKey = $("#conditionKeyValue option:selected")

            objCon.conValue =selectKey.val()
            objCon.conValueName = selectKey.text()
        } else {
            layer.alert("请选择控制值")
            return
        }
    } else if (valueType == "text") {
        if ($("#conditionKeyValueText").val()) {

            objCon.conValue = $("#conditionKeyValueText").val()
            objCon.conValueName = $("#conditionKeyValueText").val()

        } else {
            layer.alert("请输入控制值")
            return
        }
    }

    var ib = false
    $.each(objCons, function (i, item) {
        if (item.fieldName == objCon.fieldName && item.operator == objCon.operator && item.conValue == objCon.conValue) {
            layer.msg('请勿重复添加')
            ib = true
            return false
        }
    })
    if (ib == true) return

    objCons.push(objCon)
    conditionFormRender()
    clearCon()
}

function closeLayer(layerIndex) {
    if (!layerIndex) layerIndex = currentLayerIndex

    layer.close(layerIndex);
}
/*
* @author: wj
* @description: 活动连接线保存
* @date: 2019/3/5 18:30
* @param
* @return
*/
function saveCons() {

    var sourceId = flowchart.currentLine.sourceId
    var targetId = flowchart.currentLine.targetId

    $.each(objCons, function (i, item) {
        delete item["LAY_TABLE_INDEX"]
    })

    conViewTemp = objCons

    ActHttpRequest('/wf/activity/line/saveActivityLine', {
        'sourceId': sourceId,
        'targetId': targetId,
        'wfId': wfId,
        'conditions': JSON.stringify(objCons)
    }, function (data) {
        if (data.OK != "OK") {
            layer.msg('request error')
            return;
        } else {
            layer.msg('保存成功')
            layer.close(currentLayerIndex);
        }

    }, null, null, null, '加载中。。。');

}

function conditionFormRender(){
    layui.use('table', function () {
        var table = layui.table;

        table.init('formField', {
            height: '236',
            data: objCons,
            limit: 999,
            done: function () {
                $("[data-field='btnDel']").children().each(function (index) {

                    if (index > 0) {
                        $(this).html('<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="removeCon(' + index + ');">\n' +
                            '<i class="layui-icon">&#xe640;</i> 移除\n' +
                            '</button>')
                    }

                })
            }
        });
    });
}



function removeCon(index) {
    objCons.splice(index - 1, 1)
    conditionFormRender()
}

function conObj2html(conObj) {
    if (!conObj || conObj.length==0) return " "

    var strHtml = ""
    conObj.forEach(function (item) {
        if (strHtml) strHtml += "<br>"
        strHtml += item.fieldDisName
        strHtml += item.operatorName
        strHtml += item.conValueName
    })

    return strHtml
}

/*
* 获取节点执行人*/
function getExecutor(iid) {
    var url = "/wf/activity/authority/list"
    var resUsers = ""

    $.ajax({
        type: 'post',
        url: url,
        data: { "activityId": iid},
        success: function (data) {
            console.log(data)

            data.List.forEach(function (iitem) {
                if (resUsers) resUsers += " "

                var strTitle = ""
                switch (iitem.flag) {
                    case 1:
                        strTitle = "(机构)"
                        break;
                    case 3:
                        strTitle = "(岗位)"
                        break;
                    case 4:
                        strTitle = "(角色)"
                        break;
                    case 5:
                        strTitle = "(用户)"
                        break;
                    case 6:
                        strTitle = "(计算)"
                        break;
                    case 7:
                        strTitle = "(指定环节办理人)"
                        break;
                }

                resUsers += strTitle + iitem.name
            })
        },
        complete: function (XMLHttpRequest, textStatus) {},
        error: function (a, b, c) {
            // 请求出错处理,依然初始化咨询节点信息
            if (b == 'timeout') {
                layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
            } else {
                layer.alert(url + "请求异常", {title: '错误信息：'});
            }
        }
    });

    if (resUsers) {
        resUsers = resUsers.replace(/,/g, " ")
    } else {
        resUsers = "（未配置）"
    }

    return resUsers
}